import requests
import hashlib
import time

def generate_g_footer(video_url):
    """
    替代原有的JavaScript函数，使用纯Python生成动态请求头
    对应原JavaScript中的generateGFooter函数
    """
    locale = 'zh'
    qc = '6HTugjCXxR'
    
    # 1. 获取当前时间戳（毫秒级）
    timestamp = int(time.time() * 1000)
    
    # 2. 拼接字符串：link + locale + timestamp + qc
    combined_string = video_url + locale + str(timestamp) + qc
    
    # 3. 使用MD5算法对拼接后的字符串进行哈希
    # 注意：需要将字符串编码为bytes
    combined_bytes = combined_string.encode('utf-8')
    g_footer = hashlib.md5(combined_bytes).hexdigest()
    
    # 4. 返回请求头所需的对象
    return {
        'g-timestamp': str(timestamp),
        'g-footer': g_footer
    }

def main():
    """
    主函数，处理视频链接并发送API请求
    """
    try:
        # 1. 获取用户输入的视频链接并进行正则匹配
        video_url = input("请输入视频链接：")
        
        if not video_url:
            print("❌ 无效的视频链接")
            return

        # 2. 使用纯Python函数生成动态请求头（替代原有的JS调用）
        footer_data = generate_g_footer(video_url)

        # 3. 构建完整的请求头和JSON数据
        headers = {
            'accept': '*/*',
            'accept-language': 'zh',
            'content-type': 'application/json',
            'origin': 'https://snapany.com',
            'priority': 'u=1, i',
            'referer': 'https://snapany.com/',
            'sec-ch-ua': '"Not;A=Brand";v="99", "Microsoft Edge";v="139", "Chromium";v="139"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"Windows"',
            'sec-fetch-dest': 'empty',
            'sec-fetch-mode': 'cors',
            'sec-fetch-site': 'same-site',
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36 Edg/139.0.0.0',
            'g-footer': footer_data['g-footer'],
            'g-timestamp': footer_data['g-timestamp'],
        }

        json_data = {'link': video_url}

        print("\n正在发送请求...")
        
        # 4. 发送POST请求
        response = requests.post('https://api.snapany.com/v1/extract', headers=headers, json=json_data)
        response.raise_for_status()  # 检查请求是否成功

        # 5. 打印JSON响应
        print("✅ 请求成功！\n")
        print("标题:", response.json().get('text', '无标题'))
        print("视频链接:", response.json().get('medias')[0].get('resource_url', '无视频链接'))
        print("音频链接:", response.json().get('medias')[-1].get('resource_url', '无音频链接'))
        
    except requests.exceptions.RequestException as e:
        print(f"❌ 请求失败: {e}")
    except Exception as e:
        print(f"❌ 发生错误: {e}")

if __name__ == "__main__":
    main()